package czy.demo.listener;

import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * 消息监听器,必须是Bean
 * 是否继承ChannelAwareMessageListener则不一定,可以不继承
 * 考虑以下两种情况:
 * 多个监听方法同时监听一个队列时:队列中消息轮流发送给多个监听器,此时队列的exclusive必须为false,即非私有队列
 * 一个监听器监听多个队列时:每个被监听的队列消息都会发送到这个监听器
 */

/**
 * direct类型exchange的监听器,根据routingKey分发消息
 */
@Component
public class DirectListener {

    private static final Logger logger = LoggerFactory.getLogger(DirectListener.class);

    /**
     * 监听器方法注解,虽然这个注解在类上也是可用的,但是没成功
     * 这个注解的以下三个字段都用来指定监听队列,且互斥
     * queues
     * bindings
     * queuesToDeclare
     */
    @RabbitListener(
            bindings =
                    @QueueBinding(
                        value = @Queue("apple"),
                        exchange = @Exchange("direct"),
                        key = "a"
                    )
    )
    public void onAppleMessage(Message message, Channel channel) throws Exception {
        logger.info("接收到Apple队列消息: ");
        logger.info("properties: "+message.getMessageProperties());
        logger.info("body: "+new String(message.getBody()));
        /**
         * 向rabbit server确认收到消息
         * 如果acknowledge-mode: auto,则开启自动确认模式
         * 如果acknowledge-mode: manual,则开启手动确认模式
         */
        //channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
    }


    @RabbitListener(
            bindings =
            @QueueBinding(
                    value = @Queue("banana"),
                    exchange = @Exchange("direct"),
                    key = "b"
            )
    )
    public void onBananaMessage(Message message, Channel channel) throws Exception {
        logger.info("接收到Banana队列消息: ");
        logger.info("properties: " + message.getMessageProperties());
        logger.info("body: " + new String(message.getBody()));
    }


    @RabbitListener(
            bindings =
            @QueueBinding(
                    value = @Queue("orange"),
                    exchange = @Exchange("direct"),
                    key = "o"
            )
    )
    public void onOrangeMessage(Message message, Channel channel) throws Exception {
        logger.info("接收到Orange队列消息: ");
        logger.info("properties: " + message.getMessageProperties());
        logger.info("body: " + new String(message.getBody()));
    }

}
